<?php

class ElementController extends Buzz_AuthedController {

    private $mapper;
    private $authChecker;

    public function proxyimageAction() {
        header('Content-type: image/jpeg');
        readfile($this->getRequest()->getParam('url'));
        exit();
    }

    public function init() {
        /* Initialize action controller here */
        $this->mapper = new Application_Model_ElementMapper();
        $this->authChecker = new Buzz_AuthChecker();
    }

    public function indexAction() {
        $this->_helper->redirector('list');
    }

    protected function doPreDispatch() {
        $action = $this->getRequest()->getActionName();
        if ($action == "addtogroup" || $action == "unlink" || $action == "delete") {
            $id = $this->getRequest()->getParam("id");
            if (!$this->authChecker->ownsElement($id)) {
                throw new Exception("Action forbidden. You do not own this element.");
            }
        }
    }

    public function addAction() {
        $req = $this->getRequest();
        $user = Zend_Auth::getInstance()->getIdentity();
        if (!$req->isPost()) {
            $this->view->form = new Application_Form_AddElement(array('action' => '/element/add'));
            return $this->render('add');
        }

        $form = new Application_Form_AddElement();
        if (!$form->isValid($req->getPost())) {
            $this->view->form = $form;
            return $this->render('add');
        }

        // user name exists
        $values = $form->getValues();
        $query = $this->mapper;

        $elt = new Application_Model_Element(
                        null,
                        $values["url"],
                        null,
                        0,
                        0,
                        $user->id(),
                        "waiting",
                        '',
                        null
        );

        $downloader = Buzz_DownloadProxy::instance();
        $dbImage = new Application_Model_ImageMapper();
        // url based
        if ($values['url'] != '') {
            $url = $values['url'];
            if (substr($url, 0, 7) != "http://" && substr($url, 0, 8) != "https://") {
                $url = "http://" . $url;
            }
            if (preg_match("#.*\.(jpe?g|gif|png)$#i", $url)) {
                $elt->set_type('image');
                $id = $query->save($elt);
                $key = $downloader->requestDownload(Buzz_DownloadProxy::HTTP_TYPE, $url, Buzz_DownloadProxy::IMAGE_HTTPSUBTYPE, $id);
                $img_url = $url;
                $name = basename($url);
                $i = new Application_Model_Image(null, $img_url);
                $imgId = $dbImage->save($i);
                $downloader->requestImageDownload($img_url, $imgId);
            } else if (preg_match("#.*\.torrent$#i", $url)) {
                throw new Exception("Not yet implemented");
            } else if (preg_match('#(http://)?(fr\.|www\.)?youtube\.com(.*?)v=(?P<ytid>([^&])*)(.*?)#i', $url, $d)) {
                $elt->set_tech_id($d['ytid']);
                $elt->set_type('video');
                $xml = file_get_contents('http://gdata.youtube.com/feeds/api/videos/' . $d['ytid']);
                $sxml = simplexml_load_string($xml);
                $description = $sxml->content;
                $name = $sxml->title;
                $media = $sxml->children('http://search.yahoo.com/mrss/');
                $attrs = $media->group->thumbnail[0]->attributes();
                $img_url = (string) $attrs["url"];
                $i = new Application_Model_Image(null, $img_url);
                $imgId = $dbImage->save($i);
                $downloader->requestImageDownload($img_url, $imgId);
                $id = $this->mapper->save($elt);
            } else {
                $elt->set_type('link');
                $elt->set_tech_id($url);
                $name = parse_url($url, PHP_URL_HOST);
                $imgId = $downloader->requestDownload(Buzz_DownloadProxy::HTTP_TYPE, $url, Buzz_DownloadProxy::LINK_HTTPSUBTYPE, null);
                $i = $dbImage->find($imgId);
                $img_url = $i->uri();
                $id = $this->mapper->save($elt);
            }
        }
        // upload base
        else if ($form->file->receive()) {
            $url = $form->file->getFilename();
            if (preg_match("#.*\.(jpe?g|gif|png)$#i", $url)) { // image if \.(png)|(jpe?g)|(gif)$
                $elt->set_type('image');
                $id = $query->save($elt);
                $key = $downloader->requestDownload(Buzz_DownloadProxy::HTTP_TYPE, $url, Buzz_DownloadProxy::IMAGE_HTTPSUBTYPE, $id);
                $img_url = $url;
                $i = new Application_Model_Image(null, $img_url);
                $imgId = $dbImage->save($i);
                $key = $downloader->requestImageDownload($img_url, $imgId);
                $img_url = '/images/' . $downloader->getDestination($key, Buzz_DownloadProxy::HTTP_TYPE);
                $name = basename($url);
            } elseif (preg_match("#.*\.torrent$#i", $url)) { // torrent if \.torrent$
                throw new Exception("Not yet implemented");
            }
        } else {
            $this->view->form = $form;
            return $this->render('add');
        }

        $this->mapper->addToGroup($id, $values["category"]);

        $this->view->form = new Application_Form_AddMetaData(
                            array('action' => '/element/addMetaData'));
        $this->view->form->setDefault('id', $id);
        $this->view->form->setDefault('name', 'Enter name here');
        if (isset($description)) {
            $this->view->form->setDefault('description', $description);
        }

        if (isset($imgId)) {
            $this->view->form->setDefault('imgId', $imgId);
        }

        if (isset($name)) {
            $this->view->form->setDefault('name', $name);
        }

        $this->view->form->setDefault('url', $url);

        $this->view->img = $img_url;

        return $this->render('addMetaData');
    }

    public function addmetadataAction() {

        $req = $this->getRequest();
        if (!$req->isPost()) {
            $this->view->form = new Application_Form_AddMetaData(
                            array('action' => '/element/addMetaData'));
            $this->view->form->setDefault('id', $this->getRequest()->getParam('id'));
            $this->view->form->setDefault('name', 'enter name here');
            return $this->render('addMetaData');
        }

        $form = new Application_Form_AddMetaData();
        if (!$form->isValid($req->getPost())) {
            $this->view->form = $form;
            return $this->render('add-meta-data');
        }
        $values = $form->getValues();

        $imgId = $values['imgId'];
        $elt = $this->mapper->find($values['id']);
        if ($elt == null) {
            var_dump($values);
            die();
        }

        // paternity check
        // add image
        if ($values['src'] != '') {
            $dbImage = new Application_Model_ImageMapper();
            $i = new Application_Model_Image(null, $values['src']);
            $imgId = $dbImage->save($i);
            $downloader->requestImageDownload($values['src'], $imageID);
        }

        // update element infos
        $elt->set_name($values['name']);
        $this->mapper->save($elt);

        // add metadata
        $db = new Application_Model_MetaDataMapper();
        $meta = new Application_Model_Metadata(
                        null,
                        $values['id'],
                        $imgId,
                        $values['description'],
                        $values['url']
        );
        $db->save($meta);
        $this->_redirect($this->view->url(array('id' =>$values['id']), 'viewelement', true));
    }

    public function imdbsearchAction() {
        $search = $this->getRequest()->getParam('search');
        $IMDB = new Buzz_IMDB();
        $list = $IMDB->search($search);
        $this->_helper->json($list);
    }

    public function imdbinfoAction() {
        $id = $this->getRequest()->getParam('id');
        $IMDB = new Buzz_IMDB();
        $infos = $IMDB->infoById($id);
        $this->_helper->json($infos);
    }

    public function viewAction() {
        $id = $this->getRequest()->getParam("id");
        $this->view->element = $this->mapper->find($id);
        if (!$this->view->element) {
            throw new Exception("No element with id $id");
        }

        $this->view->isOwner = $this->authChecker->ownsElement($this->view->element);
        $this->view->element->fillGroups();
        $actionUrl = $this->view->url(array("id" => $id), "addtogroup", true);
        $formopts = array('action' => $actionUrl, "id" => "addToGroup");
        $this->view->addToGroupForm = new Application_Form_AddToGroup($formopts);
    }

    public function listAction() {
        $db = new Application_Model_ElementMapper();
        $this->view->elements = $db->fetchall($this->session->filter);
    }

    public function addtogroupAction() {
        $id = $this->getRequest()->getParam("id");
        $gid = $this->getRequest()->getParam("group");
        $this->mapper->addToGroup($id, $gid);
        $gmapper = new Application_Model_GroupMapper();
        $group = $gmapper->find($gid);
        $url = $this->view->url(array("id" => $gid), "groupview", true);
        $unlinkUrl = $this->view->url(array("id" => $id, "gid" => $gid), "unlink", true);
        $this->_helper->json(array("id" => $gid,
            "name" => $group->name(), "url" => $url, "unlinkUrl" => $unlinkUrl));
    }

    public function unlinkAction() {
        $id = $this->getRequest()->getParam("id");
        $gid = $this->getRequest()->getParam("gid");
        $result = $this->mapper->unlinkGroup($id, $gid);
        $this->_helper->json(array("success" => $result == 1));
    }
    
    public function removeAction()
    {
      $id = $this->getRequest()->getParam("id");
      
      $auth = new Buzz_AuthChecker();
      if (!$auth->ownsElement($id)) {
        throw new Exception("You are not authorized to perform this action.");
      }
      $this->mapper->remove($id);
      $this->_helper->redirector('list');
    }
}

